#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include <openssl/err.h>

int main() {
    // 打开私钥文件
    FILE *key_file = fopen("../../cert/rsa_server.key", "r");
    if (!key_file) {
        perror("Failed to open private key file");
        return 1;
    }

    // 读取私钥
    EVP_PKEY *private_key = PEM_read_PrivateKey(key_file, NULL, NULL, NULL);
    fclose(key_file);
    if (!private_key) {
        fprintf(stderr, "Error reading private key\n");
        ERR_print_errors_fp(stderr);
        return 1;
    }

    // 将私钥转换为 DER 格式的字节流
    unsigned char *der_data = NULL;
    int der_length = i2d_PrivateKey(private_key, &der_data);
    if (der_length <= 0) {
        fprintf(stderr, "Error converting private key to DER format\n");
        ERR_print_errors_fp(stderr);
        EVP_PKEY_free(private_key);
        return 1;
    }

    // 打印私钥的 16 进制表示
    printf("Private Key (Hexadecimal) length:%d :\n", der_length);
    BIO_dump_fp(stdout, der_data, der_length);

    // 释放资源
    OPENSSL_free(der_data);
    EVP_PKEY_free(private_key);

    return 0;
}

